#include <string.h>
#include <stdio.h>
#include <jni.h>

#include "cocos2d.h"
#include "CCTestDetails.h"

#include "unittestpp.h"
#include "src/TestRunner.h"
#include "src/TestResults.h"
#include "src/TestReporter.h"
#include "src/TestReporterStdout.h"

using namespace cocos2d;
using namespace UnitTest;

#ifdef __cplusplus
extern "C" {
#endif

jstring Java_com_cat_catropico_Catropico_executeUnitTests(JNIEnv* env, jobject thiz)
{
  // Run all tests (same as UnitTest::RunAllTests()).
  TestReporterStdout reporter;
  TestRunner runner(reporter);
  runner.RunTestsIf(Test::GetTestList(), NULL, True(), 0);
  TestResults* testResults = runner.GetTestResults();
  CCArray* failArray = testResults->GetFailArray();

  // Pass results back to Java for display.
  int bufferSize = 1024;
  int bufferThres = 1000;
  char result[bufferSize];
  if (testResults->GetFailedTestCount() > 0)
  {
	  sprintf(result, "Final results: failure\n" \
	        "%d out of %d test(s) failed (%d failure(s)).\n",
	        testResults->GetFailedTestCount(),
	        testResults->GetTotalTestCount(),
	        testResults->GetFailureCount());

	  for( int i=0; i<failArray->count(); i++ )
	  {
		  CCTestDetails* failTestDetails = (CCTestDetails*) failArray->objectAtIndex(i);
		  sprintf(result + strlen(result), "\n%s: %s failed (%i).",
				  failTestDetails->getSuiteName(),
				  failTestDetails->getTestName(),
				  failTestDetails->getLineNumber());

		  if( strlen(result) > bufferThres )
			  break;
	  }
  }
  else
  {
    sprintf(result, "Final results: success\n" \
      "%d test(s) passed.", testResults->GetTotalTestCount());
  }
  return env->NewStringUTF(result);
}

#ifdef __cplusplus
}
#endif
